import models
from db import engine, get_db
from sqlalchemy.orm import Session
from fastapi import Depends
import crud
from fastapi import FastAPI
from schema import FriendModel

# 学习网址：http://lpxz.work/posts/13038/
# 官网网址：https://fastapi.tiangolo.com/zh/learn/
# 初始化数据库
models.Base.metadata.create_all(bind=engine)


app = FastAPI(
    title="测试学习API",
    version="1.0.0",
    description="一个关于fastapi增删改查的API实例",
)

@app.post("/create_firend", summary="创建API") 
def create_firend(friend:FriendModel,  db:Session = Depends(get_db)):
    friend = crud.create_firend(db=db, first_name=friend.first_name, last_name=friend.last_name, age=friend.age)
    return {"firend":friend}


@app.get("/get_firend/{id}", summary="查询单条API")
def get_firend(id:int, db:Session = Depends(get_db)):
    friend = crud.get_firend(db=db, id=id)
    return friend

@app.get("/list_firend", summary="查询所有API")
def list_firend(db:Session = Depends(get_db)):

    firends_list = crud.list_firend(db=db)
    return firends_list

@app.put("/update_firend/{id}",summary="更新API")
def update_firend(id:int, first_name:str, last_name:str, age:int, db:Session = Depends(get_db)):
    db_friend = crud.get_firend(db=db,id=id)
    if db_friend:
        update_firend = crud.update_friend(id=id, db=db, first_name=first_name, last_name=last_name, age=age)
        return update_firend
    else:
        return {"error":f"Friend with id {id} does not exist"}

@app.delete("/delete_friend/{id}", summary="删除API")
def delete_firend(id:int, db:Session = Depends(get_db)):
    db_friend = crud.get_firend(db=db, id=id)
    if db_friend:
        return crud.delete_firend(db=db, id=id)
    else:
        return {"error": f"Friend with id {id} does not exist"}










